import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
import ENV_CONFIG from './config/env.js';
// 引入fs模块
import fs  from 'fs';

// 读取 manifest.json ，修改后重新写入
const manifestPath = `${__dirname}/manifest.json`;

let Manifest = fs.readFileSync(manifestPath, { encoding: 'utf-8' });
function replaceManifest(path, value) {
	const arr = path.split('.');
	const len = arr.length;
	const lastItem = arr[len - 1];    
	let i = 0;
	let ManifestArr = Manifest.split(/\n/);

	for (let index = 0; index < ManifestArr.length; index++) {
		const item = ManifestArr[index];
		if (new RegExp(`"${arr[i]}"`).test(item)) ++i;
		if (i === len) {
			const hasComma = /,/.test(item);
			ManifestArr[index] = item.replace(
				new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
				`"${lastItem}": ${typeof value === 'string'? '"'+value+'"' : value}${hasComma ? ',' : ''}`
			);
			break;
		}
	}
	Manifest = ManifestArr.join('\n');
}
// 具体使用，找到对应key值替换为新的值
// replaceManifest('app-plus.usingComponents', false);

const CONFIG = ENV_CONFIG[JSON.parse(process.env.UNI_CUSTOM_DEFINE).ENV_TYPE];
console.log(CONFIG);
const appid = CONFIG.appid;

replaceManifest('mp-weixin.appid', appid);

fs.writeFileSync(manifestPath, Manifest, { flag: 'w' });

export default defineConfig({
    plugins: [uni()],
    define: {
        'process.env.config': CONFIG
    },
});